package bottle.jack;
import java.util.ArrayList;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;


public class User {
	
	@Id String identity;
	String nickname;
	ArrayList<Message> messages;
	Location location;
	int region;
	UserData data;
	
	public User(String id, String nickname, Location location)
	{
		this.nickname = nickname;
		identity = id;
		this.location = location;
		messages = new ArrayList<Message>(0);
		data = new UserData();
		data.identity = id;
		data.location = location;
		data.messages = new ArrayList<Message>(0);
		data.nickname = nickname;
	}
	   @Entity
       static class UserData {
			@Id
			String identity;
			@Embedded
			ArrayList<Message> messages = new ArrayList<Message>(0);
			@Embedded
			Location location;
			@Embedded
			int region;
			@Embedded
			String nickname;
       }
	   public int AuthorNewMessage(Message message)
	   {
	     User recipient = GetNextRecipient(message);
	     if (recipient != null) {
	       Send(message, recipient);
	       return recipient.data.messages.size();
	     }
	     return -1;
	   }
	   public User GetNextRecipient(Message message)
	   {
		   Location thisLoc = MongoDAO.getInstance().GetUserById(message.currentMessageHolder).location;
		   Location destinationLoc = MongoDAO.getInstance().GetUserById(message.destination).location;
		   int iterations = message.iterationsLeft;
		   Location nextLoc = new Location(((destinationLoc.latitude-thisLoc.latitude)/iterations)+thisLoc.latitude, ((destinationLoc.longitude-thisLoc.longitude)/iterations)+thisLoc.longitude);
		   User i = MongoDAO.getInstance().GetNearestUser(nextLoc, this);
		   return i;
	   }
	   public void AddMessage(Message message)
	   {
		   messages.add(message);
		   data.messages = messages;
		   MongoDAO.getInstance().UpdateUser(this);
	   }
	   public void RemoveMessage(Message message)
	   {
		   messages.remove(message);
		   data.messages = messages;
		   MongoDAO.getInstance().UpdateUser(this);
	   }
	   public void Send(Message message, User recipient)
	   {
		   message.iterationsLeft--;
		   message.currentMessageHolder = recipient.identity;
		 //  message.
		   
		   recipient.AddMessage(message);
		   RemoveMessage(message);
	   }

	   public void UpdateLocation(Location location) {
	     this.location = location;
	     data.location = this.location;
	     MongoDAO.getInstance().UpdateUser(this);
	     
	   }

}
